import { createStore } from 'vuex'

export default createStore({
  state: {
    cartgoods: [],
    buygoods: [],
    buymoney:0,
    account:10000
  },
  mutations: {
    addcartgoods(state, item) {
      // 判断是否重复加入购物车
      let oldgoods = state.cartgoods.find(s =>
        s.iid === item.iid
      );
      if (oldgoods) {
        oldgoods.count = oldgoods.count + 1
      }
      else {
        state.cartgoods.push(item)
      }
      console.log('state!!!', state.cartgoods);
    },
    jiacount(state, item) {
      let goods = state.cartgoods.find(res => {
        return res.iid === item.iid
      })
      goods.count = goods.count + 1
    },
    jiancount(state, item) {
      let goods = state.cartgoods.find(res => {
        return res.iid === item.iid
      })
      if (goods.count === 1) {
        return
      }
      goods.count = goods.count - 1
    },
    ischeck(state,item)
    {
      let goods = state.cartgoods.find(res => {
        return res.iid === item.iid
      })
      goods.checked=!goods.checked

    },
    carttrue(state){
      state.cartgoods.forEach(item=>item.checked=true)
    },
    cartfalse(state){
      state.cartgoods.forEach(item=>item.checked=false)
    },
    clearcart(state)
    {
      let buyedgoods=state.cartgoods.filter(item=>{
        return item.checked
      })
      // 把购买商品加入已购买系列
      buyedgoods.forEach(iteming=>{
        // 找出购买的商品
        let isbuy=state.buygoods.find(itemed=>{
          return itemed.iid===iteming.iid
        })
        // 没有就添加
        if(isbuy===undefined)
        {
          state.buygoods.push(iteming)
        }
        // 有就进行数量增加
        else{
          isbuy.count=parseInt(isbuy.count)+parseInt(iteming.count)
        }
      })
      // 清空购物车
      state.cartgoods=state.cartgoods.filter(item=>{
        return item.checked===false
      })
    },
    // 更新金额
    updatebuymoney(state,money){
      state.buymoney=money
      console.log('state.buymoney',state.buymoney);
    },
    initbuymoney(state){
      state.buymoney=0
    },

    updataaccount(state,money){
      state.account=money
      console.log('state.account',state.account);
    }

  },
  getters: {
    getcartgoods(state) {
      return state.cartgoods
    },
    zong(state){
      let zprice= state.cartgoods.filter(res=>res.checked).reduce((val,item)=>{
        return val+ parseInt(item.count)*parseInt(item.price)
      },0)
      console.log("zprice1515",zprice);
      return zprice
    },

    getbuygoods(state)
    {
      return state.buygoods
    },
    getbuymoney(state){
      return state.buymoney
    },
    getaccount(state){
      return state.account
    }

  },
  actions: {

  },
  modules: {

  }
})
